package com.ruoyi.erp.task;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.oConvertUtils;
import com.ruoyi.erp.domain.XsrEfPrjQuery;
import com.ruoyi.erp.service.IERPService;
import com.ruoyi.erp.service.IXSREFPrjQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component("erpTask")
public class ErpTask {
    @Autowired
    private IERPService iErpService;
    @Autowired
    private IXSREFPrjQueryService ixsrefPrjQueryService;

    public void xmdtb(){
        System.out.println(" --- 同步任务调度开始，时间：" + DateUtils.getTime() + "---");
        List<String> erpProject = iErpService.getSyncProject();
        List<XsrEfPrjQuery> localErpProject = ixsrefPrjQueryService.selectXsrEfPrjQueryList();

        ConcurrentHashMap<String, XsrEfPrjQuery> localErpProjectMap = new ConcurrentHashMap<String, XsrEfPrjQuery>(){{
            localErpProject.forEach(p->{
                put(iErpService.getProjectIdByCode(p.getPrjCode()),p);
            });
        }};

        //ThreadPoolExecutor threadPool = EnFiUtil.getTheadPool();
        erpProject.forEach(sid->{
            //threadPool.execute(()->{
            XsrEfPrjQuery project =ixsrefPrjQueryService.getXsrEfPrjQueryByProjectId(sid);
            XsrEfPrjQuery localProject = ixsrefPrjQueryService.selectXsrEfPrjQueryById(iErpService.getProjectCodeById(sid));

            if(oConvertUtils.isNotEmpty(localProject)){
                ixsrefPrjQueryService.updateXsrEfPrjQuery(project);
            }else {
                ixsrefPrjQueryService.insertXsrEfPrjQuery(project);
            }
            localErpProjectMap.remove(sid);
            //});
        });
        //EnFiUtil.waitThreadPoolCompleted(threadPool, "同步项目完成", () -> {
        //本地清除在erp中不存在的项目
        Set<String> ids = localErpProjectMap.keySet();
        String[] ids2 = ids.toArray(new String[ids.size()]);
        if (!ids.isEmpty()) {
            ixsrefPrjQueryService.deleteXsrEfPrjQueryByIds(ids2);
        }
        //});
        System.out.println(" --- 执行完毕，时间：" + DateUtils.getTime() + "---");
    }

}
